package ee.serge.client;

import com.google.gwt.event.dom.client.ClickEvent;
import com.google.gwt.event.dom.client.ClickHandler;
import com.google.gwt.user.client.ui.Button;
import com.google.gwt.user.client.ui.FlowPanel;

import ee.serge.client.content.CalculatorContent;
import ee.serge.client.content.FullLoansContent;
import ee.serge.client.content.cp.LoginContent;
import ee.serge.service.Service;
import ee.serge.util.SimpleCallback;
import ee.serge.util.URLData;

public class Header extends FlowPanel {

   private static Header header = new Header();
   
   public static Header getInstance() {
      return header;
   }
   
   // GENERAL
   private Button button1 = new Button(CalculatorContent.getName());
   private Button button4 = new Button("All loans");
   private Button button3 = new Button("Log in");
   
   // ADMIN
   
   private Button admBtn1 = new Button("Log out");
   
   public Header() {
           
      button1.addClickHandler(new ClickHandler() {
         
         @Override
         public void onClick(ClickEvent event) {
            URLData data = CalculatorContent.getURLData();
            data.add("data", "hello");
            Move.get().goToURLData(data);
         }
      });
      button3.addClickHandler(new ClickHandler() {
         
         @Override
         public void onClick(ClickEvent event) {
            Move.get().goToURLData(LoginContent.getURLData());
         }
      });
      button4.addClickHandler(new ClickHandler() {
         
         @Override
         public void onClick(ClickEvent event) {
            Move.get().goToURLData(FullLoansContent.getURLData());
         }
      });
      add(button1);
      add(button4);
      add(button3);
      
      Service.getControlPanelService().isLoggedIn(new SimpleCallback<Boolean>() {

         @Override
         public void success(Boolean result) {
            if (result) {
               login();
            }
         }
      });
   }
   
   public void login() {
      add(admBtn1);
      admBtn1.addClickHandler(new ClickHandler() {
         
         @Override
         public void onClick(ClickEvent event) {
            Service.getControlPanelService().logout(new SimpleCallback<Void>() {

               @Override
               public void success(Void result) {
                  Move.get().goToURLData(LoginContent.getURLData());
                  logout();
               }
            });
         }
      });
   }
   
   public void logout() {
      remove(admBtn1);
   }
   
}
